package com.mz361.modules.system.service.impl;

import com.mz361.common.data.PageSort;
import com.mz361.common.enums.StatusEnum;
import com.mz361.modules.system.domain.InvoiceTitle;
import com.mz361.modules.system.repository.InvoiceTitleRepository;
import com.mz361.modules.system.service.InvoiceTitleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author niceale
 * @date 2024/07/23
 */
@Service
public class InvoiceTitleServiceImpl implements InvoiceTitleService {

    @Autowired
    private InvoiceTitleRepository invoiceTitleRepository;

    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    public InvoiceTitle getById(Long id) {
        return invoiceTitleRepository.findById(id).orElse(null);
    }

    @Override
    public List<InvoiceTitle> getAllByUserId(String userId) {
        return invoiceTitleRepository.findAllByMemeberId(userId);
    }

    @Override
    public void delByIdAndUserId(Long id, String userId) {
        invoiceTitleRepository.deleteById(id);
    }

    /**
     * 获取分页列表数据
     *
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<InvoiceTitle> getPageList(Example<InvoiceTitle> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return invoiceTitleRepository.findAll(example, page);
    }

    /**
     * 保存数据
     *
     * @param invoiceTitle 实体对象
     */
    @Override
    public InvoiceTitle save(InvoiceTitle invoiceTitle) {
        return invoiceTitleRepository.save(invoiceTitle);
    }

    @Override
    public void saveAll(List<InvoiceTitle> invoiceTitles) {
        invoiceTitleRepository.saveAll(invoiceTitles);
    }

    @Override
    public List<InvoiceTitle> getAllByUserId(String userId, Boolean isDefault) {
        return invoiceTitleRepository.findAllByMemeberIdAndIsDefault(userId, isDefault);
    }


    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return invoiceTitleRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }
}